import axios from "axios";
import {generateDownloadUuid, message} from "@/util/util";

const baseUrl = 'http://127.0.0.1:8080';

const MethodType = {
    post: "post",
    get: "get",
    put: "put",
    delete: "delete",
}

const StatusCode = {
    success: 200,
    error: 500,
}

function errorFunc(res) {
    message(res.data.msg, "error");
}

export async function getRequest(url, params, success, error = errorFunc) {
    try {
        const res = await axios({
            method: MethodType.get,
            url: baseUrl + url,
            params: params,
            headers: {
                token: localStorage.getItem("token"),
                refreshToken: localStorage.getItem("refreshToken"),
                username: localStorage.getItem("username"),
                password: localStorage.getItem("password"),
            }
        });
        if (res.data.code === StatusCode.success) {
            success(res);
        } else if (res.data.code === StatusCode.error) {
            error(res);
        }
    } catch (e) {
        message("服务未开启或后台服务出错", "error");
    }
}

export async function postRequest(url, params, data, success, error = errorFunc) {
    try {
        const res = await axios({
            method: MethodType.post,
            url: baseUrl + url,
            params: params,
            data: data,
            headers: {
                token: localStorage.getItem("token"),
                refreshToken: localStorage.getItem("refreshToken"),
                username: localStorage.getItem("username"),
                password: localStorage.getItem("password"),
            }
        });
        if (res.data.code === StatusCode.success) {
            success(res);
        } else if (res.data.code === StatusCode.error) {
            error(res);
        }
    } catch (e) {
        message("服务未开启或后台服务出错", "error");
    }
}

export async function postFileRequest(url, params, data, onUploadProgress) {
    try {
        const res = await axios({
            method: MethodType.post,
            url: baseUrl + url,
            params: params,
            data: data,
            onUploadProgress: onUploadProgress,
            headers: {
                token: localStorage.getItem("token"),
                refreshToken: localStorage.getItem("refreshToken"),
                username: localStorage.getItem("username"),
                password: localStorage.getItem("password"),
            }
        });
        if (res.data.code === StatusCode.error) {
            errorFunc(res);
        }
    } catch (e) {
        message("服务未开启或后台服务出错", "error");
    }
}

export async function getAvatar() {
    let avatarUrl = localStorage.getItem("avatarUrl")
    if (avatarUrl === "") {
        return require("@/img/1.jpg");
    }
    let imgSrc;
    await generateDownloadUuid((uuid) => {
        imgSrc = baseUrl + "/user/getAvatar/" + avatarUrl + "?uuid=" + uuid;
    });
    return imgSrc;
}
